<template>
  <div class="login-container">
    <el-card class="box-card">
      <h2 class="h-login">登录</h2>
      <el-form :model="formData" ref="loginFormRef" label-width="80px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password" autocomplete="off"></el-input>
        </el-form-item>

        <div class="denglu">
          <el-form-item>
            <el-button type="primary" @click="loginHandler">登录</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loginHandler2">注册</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: 'study7Login'
}
</script>

<script setup lang="ts">
import { reactive } from 'vue'

import { type IUserLoginInfo, apiLogin } from '@/service/study6/demo5'
import { useRouter, useRoute } from 'vue-router'
import type { LocationQuery } from 'vue-router'
const route = useRoute()
const router = useRouter()

const formData: IUserLoginInfo = reactive({
  username: '',
  password: ''
})
const loginHandler2 = () => {

}

// 执行登录
const loginHandler = async () => {
  try {
    const resData = await apiLogin(formData)

    if (resData.code !== '2000' || !resData.data) {
      throw new Error(resData.msg || '未知错误')
    }
    // 登录成功
    localStorage.setItem('token', resData.data)

    // router.replace({ path: '/studemo72/user' })
    setTimeout(() => {
      const { path, queryParams } = parseRedirect()
      router.replace({ path: '/studemo72/user' })
      router.push({ path: path, query: queryParams })
    }, 12)
  } catch (e: any) {
    alert(e.message)
  }
}

function parseRedirect(): {
  path: string
  queryParams: Record<string, string>
} {
  const query: LocationQuery = route.query
  const redirect = (query.redirect as string) ?? '/studemo72/user'

  const url = new URL(redirect, window.location.origin)
  const path = url.pathname
  const queryParams: Record<string, string> = {}

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value
  })

  return { path, queryParams }
}
</script>

<style scoped>
.denglu {
  align-content: space-between;
  display: flex;
}

.h-login {
  width: 300px;
  text-align: center;
  margin-bottom: 30px;
}

el-button {
  margin: 400px;
  width: 500px;
}

.login-container {
  display: flex;
  justify-content: center;
  margin-top: 100px;
  /* 修改了这里的值，因为之前的 `˜0px` 是无效的 */
}

.box-card {
  align-items: center;
  width: 400px;
  height: 300px;
}
</style>